package com.travel.service.impl.Pay;

import com.github.pagehelper.PageHelper;
import com.travel.exception.ResourceNotFoundException;
import com.travel.mapper.order.BookingMapper;
import com.travel.mapper.order.PaymentMapper;
import com.travel.model.dto.payment.PaymentRequest;
import com.travel.model.entity.auth.User;
import com.travel.model.entity.payment.Payment;
import com.travel.model.entity.service.Booking;
import com.travel.model.enums.PaymentStatus;
import com.travel.service.Service.PaymentService;
import com.travel.service.Service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.UUID;
//支付服务的实现
// //创建支付 处理回调 获取用户支付记录 获取支付记录 取消支付
@Service
@RequiredArgsConstructor
public class PaymentServiceImpl implements PaymentService {
    private final PaymentMapper paymentMapper;
    private final BookingMapper bookingMapper;
    private final UserService userService;

    @Override
    @Transactional
    public Payment createPayment(PaymentRequest request) {
        User currentUser = userService.getCurrentUser();
        Booking booking = bookingMapper.findById(request.getBookingId())
                .orElseThrow(() -> new ResourceNotFoundException("预订不存在"));

        Payment payment = new Payment();
        payment.setPaymentNo(generatePaymentNo());
        payment.setUser(currentUser);
        payment.setBooking(booking);
        payment.setAmount(booking.getAmount());
        payment.setStatus(PaymentStatus.PENDING);
        payment.setPaymentMethod(request.getPaymentMethod());

        paymentMapper.save(payment);
        return payment;
    }

    @Override
    public String handleCallback(String payload) {
        // 处理支付平台回调逻辑
        return "success";
    }

    @Override
    public Page<Payment> getUserPayments(Pageable pageable) {
        User currentUser = userService.getCurrentUser();
        PageHelper.startPage(pageable.getPageNumber() + 1, pageable.getPageSize());
        List<Payment> payments = paymentMapper.findByUserId(currentUser.getId());
        return new PageImpl<>(payments);
    }

    @Override
    public Payment getPaymentById(Long id) {
        return paymentMapper.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("支付记录不存在"));
    }

    @Override
    @Transactional
    public void cancelPayment(Long paymentId) {
        Payment payment = getPaymentById(paymentId);
        payment.setStatus(PaymentStatus.CANCELLED);
        paymentMapper.save(payment);
    }

    private String generatePaymentNo() {
        return "PAY" + UUID.randomUUID().toString().replace("-", "").substring(0, 16);
    }
} 
